package com.copa.ums.common.util;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;

/**
 * @author copa
 * @createDate 2022-11-02 18:25
 * @function
 */
public class IpUtil {

    /**
     * 获取登录用户的IP地址
     *
     * @param request HttpServletRequest
     * @return String
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    /**
     * 通过IP获取地址
     *
     * @param ip http://freeapi.ipip.net/ip
     * @return String
     */
    public static String getIpInfo(String ip) {
        if ("127.0.0.1".equals(ip)) {
            return "本地";
        }
        String url = "http://whois.pconline.com.cn?ip=" + ip;
        String info = "";
        try {
            Document document = JsoupUtils.getBody(url);
            for (Element form : document.getElementsByTag("form")) {
                System.out.println(form.getElementsByTag("p").get(1).text().substring(3));
                return form.getElementsByTag("p").get(1).text();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return info;
    }

//    public static void main(String[] args) {
//        getIpInfo("183.36.70.193");
//    }
}
